﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.IO.Ports;
using MySql.Data.MySqlClient;
using System.Threading;
using System.Diagnostics;

namespace StuMana.UI
{
    public partial class Students : Form
    {
        // export excel
        Services.ExcelInterface excel = null;
        
        // datagridview parameters
        List<string>[] list;
        string[] columnName;
        string query;
        string[] columnNameReal;
        int page;
        int maxpage;
        static int rowperpage;

        #region Students
        /// <summary>
        /// // serrvices
        /// </summary>
        private Services.student newstudent = new Services.student();
        private Services.SL025M rfid_reader = new Services.SL025M();
        public Services.COM connect;
        private Services.DataviewService dataview = new Services.DataviewService();

        //timer catch byteArray
        private byte[] serial_buff = new byte[40];

        private int action = 0;

        public Students()
        {
            InitializeComponent();
            
            Student_initial();
        }
        public Panel getPanel(int x, int y)
        {
            p_AddStudent.Location = new Point(x, y);
            return p_AddStudent;
        }

        // studen initial values
        private void Student_initial()
        {


            columnName = new string[] { "TagID", "Name", "BirthDay", "Gender", "Class","Account","LateTime" };
            columnNameReal = new string[] { "TagID", "Name", "BirthDay", "Gender", "Class", "Account", "LateTime" };
            query = "SELECT TagID, Name, BirthDay, Gender, Class, Account, LateTime FROM studentinfo";
            rowperpage = 10;
            page = 0;


            // button disable
            bt_update.Enabled = false;
            bt_writeTag.Enabled = false;
            bt_delete.Enabled = false;
            bt_next.Enabled = true;
            bt_previous.Enabled = true;

            // combobox initial
            cbb_gender.SelectedIndex = 0;
            cbb_class.SelectedIndex = 0;
            cbb_day.SelectedIndex = 0;
            cbb_month.SelectedIndex = 0;
            cbb_latetime.SelectedIndex = 0;

            dataview.setData(rowperpage, columnName, columnNameReal);
            dataview.DataOnDataGridViewInitial(dataGridView1,query,2,-1,pages);
            initial_button();

        }

        // tagID text changed
        private void tb_tagid_TextChanged(object sender, EventArgs e)
        {
            switch(action)
            {
                // query and show on datagridview
                case 1:
                    tb_tagid_query();
                    break;

                //remove last input character
                case 2:
                    remove_character();
                    break;

                //not acting for datagridview click
                case 3:
                    break;

                default:
                    tb_tagid_query();
                    break;
            }
        }

        //handle key down to determine whether accepted key
        private void tb_tagid_KeyDown(object sender, KeyEventArgs e)
        {
            if ((e.KeyValue >= 48 && e.KeyValue <= 57)||(e.KeyValue >= 96 && e.KeyValue <= 105))
            {
                action = 1;
                ts_label.Text = "None";
            }
            else if (e.KeyValue == 46)
            {
                action = 1;
            }
            else if (e.KeyValue != 8)
            {
                action = 2;
                ts_label.Text = "Number only";
            }            

        }

       // tagid query incase text changed
        private void tb_tagid_query()
        {    
            
            if (tb_tagid.Text == ""){
                    FormReset();
                    query = "SELECT * FROM studentinfo";
            }
            else
                    query = "SELECT * FROM studentinfo WHERE TagID LIKE '" + tb_tagid.Text+"%'";

            dataview.DataOnDataGridViewInitial(dataGridView1, query, 2, -1, pages);
            initial_button();
            
        }

        // remove the last character input
        private void remove_character()
        {
            int temp = tb_tagid.SelectionStart;
            if (temp > 0)
            {
                tb_tagid.Text = tb_tagid.Text.Remove(temp - 1, 1);
                tb_tagid.SelectionStart = temp - 1;
            }       
        }        
        
        // input year
        private void tb_year_TextChanged(object sender, EventArgs e)
        {
            for (int i = 0; i < tb_year.Text.Length; i++)
            {
                if (tb_year.Text[i] < 48 || tb_year.Text[i] > 57)
                {
                    tb_year.Text = tb_year.Text.Substring(0, tb_year.Text.Length - 1);
                    tb_year.SelectionStart = tb_year.Text.Length;
                    ts_label.Text = "Number only";
                    //  MessageBox.Show("TagID chi bao gom so");
                }
                else
                    ts_label.Text = "None";
            }   
        }

        // tag write
        private void bt_writeTag_Click(object sender, EventArgs e)
        {
            int size;
            try
            {
                rfid_reader.LogIn();
                size = connect.getdata(serial_buff);
                // ReadData from tag
                if (serial_buff[3] == 0x02 && size != 5000)
                {
                    rfid_reader.bt_write(newstudent.TagID,newstudent.Account);
                    connect.getdata(serial_buff);
                    if (serial_buff[3] == 0x00 && size != 5000)
                    {
                        ts_label.Text = "Ghi vao the thanh cong !";
                        FormReset();
                    }
                    else
                        ts_label.Text = "Ghi vao the that bai !";
                }
                else
                    ts_label.Text = "Ghi vao the that bai !";
            }
            catch (Exception es)
            {
                MessageBox.Show("Loi khong ghi tag duoc: " + es.Message, "Loi");
            }
        }

        // Initial COM connecting
        public void InitialConnect(StuMana.Services.COM conn)
        {
            connect = conn;
            rfid_reader.conn = conn.serialPort;
        }

        //set status to ts_connect
        public void setStatus(string stt)
        {
            ts_connect.Text = stt;
        }

        // datagridview header click
        private void dataGridView1_RowHeaderMouseClick(object sender, DataGridViewCellMouseEventArgs e)
        {
            int row;
            DateTime dt;
            try
            {
                action = 3;

                tb_tagid.Enabled = false;
                bt_insert.Enabled = false;
                bt_writeTag.Enabled = true;
                bt_delete.Enabled = true;
                bt_update.Enabled = true;


                row = e.RowIndex;
               
                
                tb_tagid.Text = dataGridView1.Rows[row].Cells[0].Value.ToString();
                tb_name.Text = dataGridView1.Rows[row].Cells[1].Value.ToString();
                dt = Convert.ToDateTime(dataGridView1.Rows[row].Cells[2].Value);
                cbb_day.Text = dt.Day.ToString();
                cbb_month.Text = dt.Month.ToString();
                tb_year.Text = dt.Year.ToString();
                cbb_gender.Text = dataGridView1.Rows[row].Cells[3].Value.ToString();
                cbb_class.Text = dataGridView1.Rows[row].Cells[4].Value.ToString();
                tb_account.Text = dataGridView1.Rows[row].Cells[5].Value.ToString();
                if (dataGridView1.Rows[row].Cells[6].Value.ToString() != "")
                    cbb_latetime.Text = dataGridView1.Rows[row].Cells[6].Value.ToString();
                else
                    cbb_latetime.Text = "NONE";

                student_GetInfo();
            }
            catch
            {
                row = 0;
            }
        }

        // infor reset
        private void FormReset()
        {
            bt_writeTag.Enabled = false;
            bt_insert.Enabled = true;
            bt_delete.Enabled = false;
            bt_update.Enabled = false;


            tb_tagid.Enabled = true;
            tb_name.Enabled = true;
            cbb_class.Enabled = true;
            cbb_day.Enabled = true;
            cbb_gender.Enabled = true;
            cbb_month.Enabled = true;
            tb_year.Enabled = true;
            tb_account.Enabled = true;   
 
            tb_name.Text = "";
            cbb_class.SelectedIndex = 0;
            cbb_day.SelectedIndex = 0;
            cbb_gender.SelectedIndex = 0;
            cbb_month.SelectedIndex = 0;
            tb_year.Text = "";
            tb_account.Text = "0";
            tb_tagid.Text = "";
        }

        // insert click
        private void bt_insert_Click(object sender, EventArgs e)
        {
            try
            {
                student_GetInfo();
                if (newstudent.AddNewStudent())
                {
                    ts_label.Text = "Write DB successfully.";
                    // refresh datagrid
                    query = "SELECT * FROM studentinfo";
                    dataview.DataOnDataGridViewInitial(dataGridView1, query, 2, -1, pages);
                    dataview.viewdata(dataGridView1,pages);
                    initial_button();



                    bt_writeTag.Enabled = true;
                    bt_insert.Enabled = false;

                    tb_tagid.Enabled = false;
                    tb_name.Enabled = false;
                    cbb_class.Enabled = false;
                    cbb_day.Enabled = false;
                    cbb_gender.Enabled = false;
                    cbb_month.Enabled = false;
                    tb_year.Enabled = false;
                    tb_account.Enabled = false;
                }
                else
                    ts_label.Text = "Write DB failed";
                newstudent.CloseConnect();
            }
            catch (Exception ex)
            {
                MessageBox.Show("Input wrong. Please full all blanks.\n" + ex.Message, "Requirement");
            }
        }

        // datagrid view selected row
        private void datagrid_selectedrow(string TagID)
        {
            int rowNumber = dataGridView1.RowCount;
            for (int j = 0; j < rowNumber; j++)
            {
                if (dataGridView1.Rows[j].Cells[0].Value.ToString() == TagID)
                {
                    dataGridView1.CurrentRow.Selected = false;
                    dataGridView1.Rows[j].Selected = true;
                    break;
                }
            }
        }

        // delete account
        private void bt_delete_Click(object sender, EventArgs e)
        {
            
            DialogResult confirm = MessageBox.Show("Are you sure delete "+tb_name.Text+" ?", "Delete Alert", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
            if (confirm == DialogResult.Yes)
            {
                if (newstudent.delete_account(tb_tagid.Text))
                {
                    FormReset();
                    Student_initial();
                }
            }
            dataview.viewdata(dataGridView1, pages);
        }

        // update account
        private void bt_update_Click(object sender, EventArgs e)
        {
            DialogResult confirm = MessageBox.Show("Are you sure update: " + tb_name.Text + " ?", "Delete Alert", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
            try
                {
                    if (confirm == DialogResult.Yes)
                    {                
                        student_GetInfo();
                        if (newstudent.update_account(tb_tagid.Text))
                        {
                            FormReset();
                            Student_initial();
                        }
                        ts_label.Text = "Update " + tb_name.Text + " information succesfully";
                    }
                    else
                        ts_label.Text = "Update " + tb_name.Text + " information failed";
                    dataview.viewdata(dataGridView1, pages);

                    
                }
            catch (Exception ex)
            {
                MessageBox.Show("Input wrong. Please full all blanks.\n" + ex.Message, "Requirement");
            }
        }

        // assign value from form to student attributes
        private void student_GetInfo()
        {
            newstudent.TagID = int.Parse(tb_tagid.Text);
            newstudent.Name = tb_name.Text;
            if (tb_year.Text != "")
                newstudent.Birthday = tb_year.Text + "-" + cbb_month.SelectedItem.ToString() + "-" + cbb_day.SelectedItem.ToString();
            else
                throw new Exception("Please input year of birth (maybe input the 2 last number)");
            newstudent.Gender = cbb_gender.SelectedItem.ToString();
            newstudent.Class = cbb_class.SelectedItem.ToString();
            
            if (tb_account.Text != "")
                newstudent.Account = int.Parse(tb_account.Text);
            
            if (int.Parse(tb_account.Text) >= 2147483647)
                throw new Exception("The number input so large");
            else newstudent.Account = int.Parse(tb_account.Text);

            if (cbb_latetime.Text != "NONE")
                newstudent.LateTime = cbb_latetime.Text;
            else
                newstudent.LateTime = null;
                

            
            // out of area
            newstudent.InOut = false;
        }

        //Form reset
        private void bt_reset_Click(object sender, EventArgs e)
        {
            FormReset();
            Student_initial();
        }

        private void export_Click(object sender, EventArgs e)
        {
            list = dataview.GetList();
            excel = new Services.ExcelInterface(list,columnName,2,2);
        }
        private void initial_button()
        {
            page = dataview.GetPage();
            maxpage = dataview.GetMaxPage();
            if (page == maxpage)
                bt_next.Enabled = false;
            bt_previous.Enabled = false;
        }

        private void bt_next_Click(object sender, EventArgs e)
        {
            page = dataview.PageIncre();
            bt_previous.Enabled = true;
            if (page >= maxpage)
                bt_next.Enabled = false;
            dataview.viewdata(this.dataGridView1, pages);

        }

        private void bt_previous_Click(object sender, EventArgs e)
        {
            page = dataview.PageDecre();
            bt_next.Enabled = true;
            if (page <= 0)
                bt_previous.Enabled = false;
            dataview.viewdata(this.dataGridView1, pages);
        }
        #endregion

  
    }
}
